
const mssql =  require('../lib/mssql')
const sqlite =  require('../lib/sqlite')
const tables =  require('../config/tables')
const sql = require('sql');
const pinyin = require("node-pinyin");




class CheckController {

  static async list(ctx){
   
  
    sql.setDialect('sqlite');

    let query = tables.checked.select('*').toQuery();
    let raw = await sqlite(query.text, query.values);
    if(raw.length >0){
      ctx.body = JSON.parse(raw[0].list);
    }else{
        ctx.body = []
    }
  }
  static async download(ctx){
  
    sql.setDialect('sqlite');
    let query = tables.checked.select('*').toQuery();
    let raw = await sqlite(query.text, query.values)
    ctx.body =  raw[0];
  }
  
  static async result(ctx){

  
    let request = ctx.request;
    let req_query = request.query;
    if(req_query.value){
        sql.setDialect('sqlite');
        let query = tables.kv.replace(tables.kv.key.value("check-result"),tables.kv.value.value(req_query.value)).toQuery();
        let raw = await sqlite(query.text, query.values)
    }else{
        
        sql.setDialect('sqlite');
        let val = {};
        val.checked = ["a","b","c"];
        val.lost = ["e","f","c"];
        val.extra = ["e","f","c"];
        let query = tables.kv.replace(tables.kv.key.value("check-result"),tables.kv.value.value(JSON.stringify(val))).toQuery();
        let raw = await sqlite(query.text, query.values)
    }
    ctx.body =  req_query;
  }
  static async upload(ctx){
  
    if(ctx.request.body &&  ctx.request.body.checks&&  ctx.request.body.checks){
        sql.setDialect('sqlite');
        let check_drop = tables.checked.drop().ifExists().toQuery();
        let check_create = tables.checked.create().ifNotExists().toQuery();
    
        await sqlite(check_drop.text, check_drop.values)
        await sqlite(check_create.text, check_create.values)

    
        const post = ctx.request.body;

        sql.setDialect('sqlite');
        let query = tables.checked.insert( tables.checked.check.value(JSON.stringify(post.checks)), tables.checked.list.value(JSON.stringify(post.list))).toQuery();
        await sqlite(query.text, query.values)
        console.log(query.text);
        ctx.body = post;
    }else{
    
        ctx.body ={};
    }
  } 
 
}

module.exports = CheckController